package com.xk857.simpleeffect.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.reflect.TypeToken;
import com.xk857.simpleeffect.AppNoticeActivity;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.Customer;
import com.xk857.simpleeffect.domain.param.RegisterParam;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.lang.reflect.Type;
import java.util.function.Consumer;

import cn.hutool.core.util.StrUtil;

public class RegisterFragment extends Fragment {

    private View view;

    private Consumer<Integer> consumer;
    private Consumer<Customer> goLogin;
    private Button sendCodeBtn;
    private int sendNum = 0;
    private EditText phoneEdit;
    private EditText pwdEdit;
    private EditText pwdConfirmEdit;
    private EditText authCodeEdit;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_register, container, false);
        TextView goLoginBtn = view.findViewById(R.id.go_login_btn);
        goLoginBtn.setOnClickListener(v -> consumer.accept(0));
        initView();
        return view;
    }

    private void initView() {
        sendCodeBtn = view.findViewById(R.id.send_code_btn);
        phoneEdit = (EditText) view.findViewById(R.id.phone_edit);
        pwdEdit = (EditText) view.findViewById(R.id.pwd_edit);
        pwdConfirmEdit = (EditText) view.findViewById(R.id.pwd_confirm_edit);
        authCodeEdit = (EditText) view.findViewById(R.id.auth_code_edit);

        sendCodeBtn.setOnClickListener(v -> {
            if (StrUtil.hasBlank(phoneEdit.getText())) {
                if (getActivity() != null) {
                    XToast.normal(getActivity(), "请先输入手机号").show();
                }
                return;
            }
            if (getActivity()!=null) {
                XToast.info(getActivity(), "请注意来自【星空小屋】的短信").show();
            }
            Type type = new TypeToken<Result<Boolean>>() {}.getType();
            OkHttpUtils.getInstance().get(getActivity(), OkHttpUtils.BASE_URL + "/api/v1/customer/send/code/" + phoneEdit.getText(), type, true, (Consumer<Boolean>) b -> {
                if (sendNum <= 0) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> sendCodeBtn.setEnabled(false));
                    }
                    sendNum = 60;
                    new Thread(() -> {
                        while (sendNum > 0) {
                            if (getActivity() == null) {
                                break;
                            }

                            if (getActivity() != null) {
                                getActivity().runOnUiThread(() -> sendCodeBtn.setText(sendNum + "s"));
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                            sendNum--;
                        }
                        if (getActivity()!=null) {
                            getActivity().runOnUiThread(() -> {
                                sendCodeBtn.setEnabled(true);
                                sendCodeBtn.setText("发送验证码");
                            });
                        }
                    }).start();
                }
            });
        });

        phoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                System.out.println("count=" + count);
                if (s.length() < 8) {
                    sendCodeBtn.setEnabled(false);
                }
                if (s.length() >= 8 && sendNum <= 0) {
                    sendCodeBtn.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        Button registerBtn = view.findViewById(R.id.register_btn);
        registerBtn.setOnClickListener(v -> {
            if (getActivity() != null) {
                if (phoneEdit.getText().toString().length() < 10) {
                    XToast.error(getActivity(),"请输入正确的手机号码").show();
                    return;
                }
                if (pwdEdit.getText().toString().length() < 6) {
                    XToast.error(getActivity(),"密码不能少于6位数").show();
                    return;
                }
                if (!pwdEdit.getText().toString().equals(pwdConfirmEdit.getText().toString())) {
                    XToast.error(getActivity(),"两次输入的密码不一致").show();
                    return;
                }
                if (authCodeEdit.getText().toString().length() < 4) {
                    XToast.error(getActivity(),"请输入验证码").show();
                    return;
                }
            }
            Type type = new TypeToken<Result<Customer>>() {}.getType();
            RegisterParam param = new RegisterParam();
            param.setCode(authCodeEdit.getText().toString());
            param.setPassword(pwdEdit.getText().toString());
            param.setUsername(phoneEdit.getText().toString());
            OkHttpUtils.getInstance().post(getActivity(), RequestEnum.REGISTER, type,param, true, (Consumer<Customer>) customer -> {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        XToast.success(getActivity(), "注册成功").show();
                        goLogin.accept(customer);
                    });
                }
            });
        });

        TextView userAboutText = view.findViewById(R.id.user_about_text);
        TextView privateAboutText = view.findViewById(R.id.private_about_text);
        userAboutText.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AppNoticeActivity.class);
            intent.putExtra("isPrivate", false);
            startActivity(intent);
        });
        privateAboutText.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AppNoticeActivity.class);
            intent.putExtra("isPrivate", true);
            startActivity(intent);
        });
    }

    public void setOnClickListener(Consumer<Integer> consumer) {
        this.consumer = consumer;
    }
    public void setGoLogin(Consumer<Customer> consumer) {
        this.goLogin = consumer;
    }
}
